<template>
  <div class="">
    <a-card :bordered="false">
      <a-form
        ref="formRef"
        :model="formData"
        class="form"
        :label-col-props="{ span: 8 }"
        :wrapper-col-props="{ span: 16 }"
      >
        <a-form-item label="头像" field="avatar">
          <a-upload
            :custom-request="customRequest"
            :show-upload-button="true"
            :show-file-list="false"
            @change="uploadChange"
          >
            <template #upload-button>
              <a-avatar :size="100" class="info-avatar">
                <template #trigger-icon>
                  <icon-camera />
                </template>
                <img v-if="singleFile.url" :src="singleFile.url"/>
              </a-avatar>
            </template>
          </a-upload>
        </a-form-item>
        <a-form-item
          label="账号"
          field="username"
          :rules="[
            {
              required: true,
              message: '账号不能为空',
            },
          ]"
        >
          <a-input v-model="formData.username" placeholder="请输入账号" disabled style="width: 50%"/>
        </a-form-item>
        <a-form-item
          label="昵称"
          field="nickname"
          :rules="[
            {
              required: true,
              message: '昵称不能为空',
            },
          ]"
        >
          <a-input v-model="formData.nickname" placeholder="请输入昵称" style="width: 50%"/>
        </a-form-item>
        <a-form-item label="手机号" field="phone">
          <a-input v-model="formData.phone" style="width: 50%"/>
        </a-form-item>
        <a-form-item label="邮箱" field="email">
          <a-input v-model="formData.email" style="width: 50%"/>
        </a-form-item>
        <a-form-item field="remark" label="备注">
          <a-textarea v-model="formData.remark" allow-clear :max-length="{ length: 120, errorOnly: true }" show-word-limit style="width: 50%"/>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="submit()">
              <icon-check /> 保存
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script setup>
  import { ref, reactive } from 'vue';
  import { Message } from '@arco-design/web-vue';

  import { useAdminStore } from '@/store';
  import { apiUpload } from '@/api/common';
  import { saveProfile } from '@/api/admin';

  const adminStore = useAdminStore();

  const formRef = ref();
  const formData = reactive({
    ...adminStore.$state
  });
  const singleFile = ref({
    url: adminStore.full_avatar,
    path: adminStore.avatar,
    field: 'avatar',
  });

  const submit = async () => {
    const ruleRes = await formRef.value?.validate();
    if (!ruleRes) {
      const res = await saveProfile(formData);
      if (res.status === 1) {
        adminStore.setInfo(formData);
        Message.success('成功！');
      } else {
        Message.info(res.msg);
      }
    }
  };
  const reset = async () => {
    await formRef.value?.resetFields();
  };

  const uploadChange = (fileItemList, fileItem) => {
    const { response } = fileItem;
    if (response) {
      // 上传
      if (response.status === 1) {
        singleFile.value.url = response.data.src;
        singleFile.value.path = response.data.filepath;
        formData.full_avatar = response.data.src;
        formData.avatar = response.data.filepath;
      }
    }
  };
  const customRequest = (options) => {
    const controller = new AbortController();
    (async function requestWrap() {
      const {
        onProgress,
        onError,
        onSuccess,
        fileItem,
        name = 'file',
      } = options;
      onProgress(20);
      const formData = new FormData();
      formData.append(name, fileItem.file);
      const onUploadProgress = (event) => {
        let percent;
        if (event.total > 0) {
          percent = (event.loaded / event.total) * 100;
        }
        onProgress(parseInt(String(percent), 10), event);
      };

      try {
        const res = await apiUpload(formData, {
          controller,
          onUploadProgress,
        });
        onSuccess(res);
      } catch (error) {
        onError(error);
      }
    })();
    return {
      abort() {
        controller.abort();
      },
    };
  };
</script>

<script>
  export default {
    name: 'Profile',
  };
</script>

<style scoped lang="less">
  .wrapper {
    padding: 20px 0 0 20px;
    min-height: 580px;
    background-color: var(--color-bg-2);
    border-radius: 4px;
  }

  :deep(.section-title) {
    margin-top: 0;
    margin-bottom: 16px;
    font-size: 14px;
  }
</style>
